<template>
  <div
    :class="{ fullscreen: flagFullscreen }"
    :style="{ width: containerWidth }"
    class="tinymce-container"
  >
    <textarea :id="tinymceId" class="tinymce-textarea" />
    <div class="tinymce-btn-upload">
      <image-uploader class="uploader" @setUploadResult="getUploadResultListImage($event)" />
      <file-uploader class="uploader" @setUploadResult="getUploadResultListFile($event)" />
    </div>
  </div>
</template>

<script>
/**
 * docs:
 * https://panjiachen.github.io/vue-element-admin-site/feature/component/rich-editor.html#tinymce
 */
import imageUploader from '@c/UploadImages2Local'
import fileUploader from '@c/UploadFiles2Local'
import plugins from './plugins'
import toolbar from './toolbar'
import load from './dynamicLoadScript'

// why use this cdn, detail see https://github.com/PanJiaChen/tinymce-all-in-one
// const tinymceCDN = 'https://cdn.jsdelivr.net/npm/tinymce-all-in-one@4.9.3/tinymce.min.js'
const tinymceCDN = 'https://cdn.tiny.cloud/1/n9zcdu5unmzgvp25xsefs4f2npngjpdiurivki0yvml4o5xn/tinymce/5/tinymce.min.js'
// const tinymceCDN = 'https://cdn.tiny.cloud/1/n9zcdu5unmzgvp25xsefs4f2npngjpdiurivki0yvml4o5xn/tinymce/6/tinymce.min.js'
// const tinymceCDN = '/static/js/tinymce.5.10.6.min.js'
import {
  defineComponent,
  ref,
  onMounted,
  watch,
  computed,
  onActivated,
  onDeactivated,
  onUnmounted,
  nextTick,
} from 'vue'
import { toastError } from '@/utils/toast'
export default defineComponent({
  name: 'TinymceCom',
  components: { imageUploader, fileUploader },
  props: {
    id: {
      type: String,
      default: function () {
        return 'vue-tinymce-' + +new Date() + ((Math.random() * 1000).toFixed(0) + '')
      },
    },
    value: {
      type: String,
      default: '',
    },
    toolbar: {
      type: Array,
      required: false,
      default() {
        return []
      },
    },
    menubar: {
      type: String,
      default: 'file edit insert view format table',
    },
    width: {
      type: [Number, String],
      required: false,
      default: 'auto',
    },
    height: {
      type: [Number, String],
      required: false,
      default: 600,
    },
  },
  emit: ['update:input'],
  setup(props, { emit }) {
    const hasChange = ref(false)
    const hasInit = ref(false)
    const tinymceId = ref(props.id)
    const flagFullscreen = ref(false)
    const languageTypeList = ref({
      en: 'en',
      zh: 'zh_CN',
      es: 'es_MX',
      ja: 'ja',
    })

    const containerWidth = computed(() => {
      const width = props.width
      if (/^[\d]+(\.[\d]+)?$/.test(width)) {
        // matches `100`, `'100'`
        return `${width}px`
      }
      return width
    })

    const init = () => {
      // dynamic load tinymce from cdn
      load(tinymceCDN, (err) => {
        if (err) {
          toastError(err.message)
          return
        }
        initTinymce()
      })
    }
    const initTinymce = () => {
      window.tinymce.init({
        selector: `#${props.id}`,
        language: languageTypeList.value['zh'],
        height: props.height,
        body_class: 'panel-body ',
        object_resizing: false,
        toolbar: props.toolbar.length > 0 ? props.toolbar : toolbar,
        menubar: props.menubar,
        plugins: plugins,
        end_container_on_empty_block: true,
        powerpaste_word_import: 'clean',
        code_dialog_height: 450,
        code_dialog_width: 1000,
        advlist_bullet_styles: 'square',
        advlist_number_styles: 'default',
        // imagetools_cors_hosts: ['www.tinymce.com', 'codepen.io'],
        default_link_target: '_blank',
        link_title: false,
        // inserting nonbreaking space &nbsp; need Nonbreaking Space Plugin
        nonbreaking_force_tab: true,
        // 初始化编辑器实例时要执行的函数
        init_instance_callback: (editor) => {
          console.log('init_instance_callback props.value', props.value)
          if (props.value) {
            // editor.setContent(props.value)
            setContent(props.value)
          }
          hasInit.value = true
          editor.on('NodeChange Change KeyUp SetContent', () => {
            hasChange.value = true
            // emit('input', editor.getContent())
            emit('input', getContent())
          })
        },
        setup(editor) {
          editor.on('FullscreenStateChanged', (e) => {
            flagFullscreen.value = e.state
          })
        },
        // it will try to keep these URLs intact
        // https://www.tiny.cloud/docs-3x/reference/configuration/Configuration3x@convert_urls/
        // https://stackoverflow.com/questions/5196205/disable-tinymce-absolute-to-relative-url-conversions
        convert_urls: false,
        // 整合七牛上传
        // images_dataimg_filter(img) {
        //   setTimeout(() => {
        //     const $image = $(img);
        //     $image.removeAttr('width');
        //     $image.removeAttr('height');
        //     if ($image[0].height && $image[0].width) {
        //       $image.attr('data-wscntype', 'image');
        //       $image.attr('data-wscnh', $image[0].height);
        //       $image.attr('data-wscnw', $image[0].width);
        //       $image.addClass('wscnph');
        //     }
        //   }, 0);
        //   return img
        // },
        // images_upload_handler(blobInfo, success, failure, progress) {
        //   progress(0);
        //   const token = _this.$store.getters.token;
        //   getToken(token).then(response => {
        //     const url = response.data.qiniu_url;
        //     const formData = new FormData();
        //     formData.append('token', response.data.qiniu_token);
        //     formData.append('key', response.data.qiniu_key);
        //     formData.append('file', blobInfo.blob(), url);
        //     upload(formData).then(() => {
        //       success(url);
        //       progress(100);
        //     })
        //   }).catch(err => {
        //     failure('出现未知问题，刷新页面，或者联系程序员')
        //     console.log(err);
        //   });
        // },
      })
    }
    const destroyTinymce = () => {
      const tinymce = window.tinymce.get(tinymceId.value)
      if (flagFullscreen.value) {
        tinymce.execCommand('mceFullScreen')
      }

      if (tinymce) {
        tinymce.destroy()
      }
    }
    // 设置内容
    const setContent = (value) => {
      window.tinymce.get(tinymceId.value).setContent(value)
    }
    // 读取内容
    const getContent = () => {
      window.tinymce.get(tinymceId.value).getContent()
    }
    // 得到上传多张图片的返回值
    const getUploadResultListImage = (val) => {
      val.forEach((v) => {
        const html = '<p style="text-align:center;"><img src="' + v + '"></p>'
        window.tinymce.get(tinymceId.value).insertContent(html)
      })
    }
    // 得到上传多个文件的返回值
    const getUploadResultListFile = (val) => {
      val.forEach((v) => {
        let html = '<p><a style="font-size:16px;" target="_blank"'
        html += ' href="' + v.url + '">'
        html += '点此下载： ' + v.fileName + '</a></p>'
        window.tinymce.get(tinymceId.value).insertContent(html)
      })
    }

    onMounted(() => {
      init()
    })

    onActivated(() => {
      if (window.tinymce) {
        initTinymce()
      }
    })

    onDeactivated(() => {
      destroyTinymce()
    })

    onUnmounted(() => {
      destroyTinymce()
    })

    watch(
      () => props.value,
      // () => [props.value],
      (val) => {
        console.log('watch props.value', val)
        if (!hasChange.value && hasInit.value) {
          nextTick(() => window.tinymce.get(tinymceId.value).setContent(val || ''))
        }
      }
    )

    return {
      hasChange,
      hasInit,
      tinymceId,
      flagFullscreen,
      languageTypeList,
      containerWidth,
      init,
      initTinymce,
      destroyTinymce,
      setContent,
      getContent,
      getUploadResultListImage,
      getUploadResultListFile,
    }
  },
})
</script>

<style lang="scss" scoped>
// .tinymce-container {
//   position: relative;
//   line-height: normal;
// }
// .tinymce-container {
//   :deep(.mce-fullscreen) {
//     // elementUI在初始化时定义了z-index为100
//     z-index: 200;
//   }
// }
// .tinymce-textarea {
//   visibility: hidden;
//   z-index: -1;
// }

// 上传内容图片及附件按钮区
.tinymce-btn-upload {
  position: absolute;
  right: 4px;
  top: 5px;
  z-index: 201;
  .uploader {
    float: left;
    margin-left: 5px;
  }
}
.fullscreen .tinymce-btn-upload {
  position: fixed;
}
</style>
